//
//  RegisterViewController.m
//  CenturyInterconnection
//
//  Created by Tian Wei You on 16/4/11.
//  Copyright © 2016年 Shanghai DuRui Information Technology Company. All rights reserved.
//

#import "RegisterViewController.h"
#import "ShoppingListViewController.h"

#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>



@interface RegisterViewController ()

@property(nonatomic,strong)UIButton *registerButton;
@property(nonatomic,strong)UIButton *loginButton;

@property(nonatomic,strong)UIView *BGView1;
@property(nonatomic,strong)UIView *BGView2;

@property(nonatomic,strong)UITextField *EmailTextField1;
//@property(nonatomic,strong)UITextField *phoneTextField1;
@property(nonatomic,strong)UITextField *passwordTextField1;
@property(nonatomic,strong)UITextField *verifyPasswordTF1;

@property(nonatomic,strong)UITextField *phoneTextField2;
@property(nonatomic,strong)UITextField *EmailTextField2;
@property(nonatomic,strong)UITextField *passwordTextField2;


@property (nonatomic,retain) UIButton * facebookButton;

@property (nonatomic,retain) UIImageView * fengeimage;

@property (nonatomic,assign) BOOL isFaceRegister;

@end

@implementation RegisterViewController

//Register
-(UIView *)BGView1{
    if (!_BGView1) {
        _BGView1=[[UIView alloc]initWithFrame:CGRectMake(0, ACTUAL_HEIGHT(180), KScreenWidth,KScreenHeight-ACTUAL_HEIGHT(180))];
        //        _BGView1.backgroundColor=[UIColor blueColor];
        
        for (int i=0; i<3; i++) {
            UIView *view1=[[UIView alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(22.5), ACTUAL_HEIGHT(65)*i, ACTUAL_WIDTH(330), ACTUAL_HEIGHT(50))];
            view1.layer.borderColor=RGBCOLOR(208, 208, 208, 1).CGColor;
            view1.layer.borderWidth=2;
            view1.backgroundColor=[UIColor whiteColor];
            [_BGView1 addSubview:view1];
        }
        
        _EmailTextField1=[[UITextField alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(35), ACTUAL_HEIGHT(2), ACTUAL_WIDTH(315), ACTUAL_HEIGHT(46))];
        //      _EmailTextField1.backgroundColor=[UIColor yellowColor];
        _EmailTextField1.placeholder=@"  E-MAIL＊";
        _EmailTextField1.keyboardType=UIKeyboardTypeEmailAddress;
        [_BGView1 addSubview:_EmailTextField1];
        
        //        _phoneTextField1=[[UITextField alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(35), ACTUAL_HEIGHT(67), ACTUAL_WIDTH(318), ACTUAL_HEIGHT(46))];
        //        _phoneTextField1.backgroundColor=[UIColor whiteColor];
        //        _phoneTextField1.placeholder=@"  TELEPHONE＊";
        //        _phoneTextField1.textColor=[UIColor blackColor];
        ////        _phoneTextField1.backgroundColor=[UIColor yellowColor];
        //        _phoneTextField1.keyboardType=UIKeyboardTypeNumberPad;
        //        [_BGView1 addSubview:_phoneTextField1];
        
        //ACTUAL_HEIGHT(132) 改成 67
        _passwordTextField1=[[UITextField alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(35), ACTUAL_HEIGHT(67), ACTUAL_WIDTH(315), ACTUAL_HEIGHT(46))];
        _passwordTextField1.backgroundColor=[UIColor whiteColor];
        _passwordTextField1.placeholder=@"  PASSWORD＊";
        //        _passwordTextField1.backgroundColor=[UIColor yellowColor];
        _passwordTextField1.secureTextEntry = YES;
        _passwordTextField1.keyboardType=UIKeyboardTypeNamePhonePad;
        [_BGView1 addSubview:_passwordTextField1];
        
        //ACTUAL_HEIGHT(197) 改成 132
        _verifyPasswordTF1=[[UITextField alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(35), ACTUAL_HEIGHT(132), ACTUAL_WIDTH(315), ACTUAL_HEIGHT(46))];
        _verifyPasswordTF1.backgroundColor=[UIColor whiteColor];
        _verifyPasswordTF1.placeholder=@"  VERIFY PASSWORD＊";
        //        _verifyPasswordTF1.backgroundColor=[UIColor yellowColor];
        _verifyPasswordTF1.secureTextEntry=YES;
        _verifyPasswordTF1.keyboardType=UIKeyboardTypeNamePhonePad;
        [_BGView1 addSubview:_verifyPasswordTF1];
        
        //ACTUAL_HEIGHT(260) 改成 197
        UIButton *creatAccountButton=[[UIButton alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(22.5), ACTUAL_HEIGHT(197), ACTUAL_WIDTH(330), ACTUAL_HEIGHT(50))];
        creatAccountButton.backgroundColor=[UIColor blackColor];
        [creatAccountButton setTitle:@"CREATE ACCTROUNT" forState:0];
        creatAccountButton.titleLabel.font = FONT_SYSTEM_24;
        [creatAccountButton addTarget:self action:@selector(gotoCreatAccount) forControlEvents:UIControlEventTouchUpInside];
        [_BGView1 addSubview:creatAccountButton];
    }
    return _BGView1;
}

//Login
-(UIView *)BGView2{
    if (!_BGView2) {
        _BGView2=[[UIView alloc]initWithFrame:CGRectMake(0, ACTUAL_HEIGHT(180), KScreenWidth,KScreenHeight-ACTUAL_HEIGHT(180))];
        //        _BGView2.backgroundColor=[UIColor orangeColor];
        
        UIView *view1=[[UIView alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(22.5), ACTUAL_HEIGHT(0), ACTUAL_WIDTH(330), ACTUAL_HEIGHT(50))];
        view1.layer.borderColor=RGBCOLOR(208, 208, 208, 1).CGColor;
        view1.layer.borderWidth=2;
        view1.backgroundColor=[UIColor whiteColor];
        [_BGView2 addSubview:view1];
        
        _EmailTextField2=[[UITextField alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(35), ACTUAL_HEIGHT(2), ACTUAL_WIDTH(315), ACTUAL_HEIGHT(46))];
        _EmailTextField2.backgroundColor=[UIColor whiteColor];
        _EmailTextField2.placeholder=@"  E-MAIL＊";
        _EmailTextField2.keyboardType=UIKeyboardTypeEmailAddress;
        //        _EmailTextField2.backgroundColor=[UIColor yellowColor];
        [_BGView2 addSubview:_EmailTextField2];
        
        UIView *view2=[[UIView alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(22.5), ACTUAL_HEIGHT(67), ACTUAL_WIDTH(330), ACTUAL_HEIGHT(50))];
        view2.layer.borderColor=RGBCOLOR(208, 208, 208, 1).CGColor;
        view2.layer.borderWidth=2;
        view2.backgroundColor=[UIColor whiteColor];
        [_BGView2 addSubview:view2];
        
        _passwordTextField2=[[UITextField alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(35), ACTUAL_HEIGHT(69), ACTUAL_WIDTH(315), ACTUAL_HEIGHT(46))];
        _passwordTextField2.backgroundColor=[UIColor whiteColor];
        _passwordTextField2.placeholder=@"  PASSWORD＊";
        _passwordTextField2.keyboardType=UIKeyboardTypeNamePhonePad;
        //        _passwordTextField2.backgroundColor=[UIColor yellowColor];
        _passwordTextField2.secureTextEntry=YES;
        [_BGView2 addSubview:_passwordTextField2];
        
        UIButton *loginButton=[[UIButton alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(22.5), ACTUAL_HEIGHT(130), ACTUAL_WIDTH(330), ACTUAL_HEIGHT(50))];
        loginButton.backgroundColor=[UIColor blackColor];
        [loginButton setTitle:@"LOGIN" forState:0];
        [loginButton addTarget:self action:@selector(gotoLogin) forControlEvents:UIControlEventTouchUpInside];
        [_BGView2 addSubview:loginButton];
        
    }
    
    return _BGView2;
}

#pragma mark - viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //导航栏
    [self makeNaviButton];
    
    [self BGView1];
    [self BGView2];
    //    facebook登录按钮
    [self creatFaceBookButton];
    //view
    [self makeView];
    
    [self openRegisterView];
    
    self.view.backgroundColor=[UIColor whiteColor];
    
    //    [self.view bringSubviewToFront:_facebookButton];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"RegisterPage"];//("PageOne"为页面名称，可自定义)
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"RegisterPage"];
}

-(void)creatFaceBookButton
{
    _fengeimage = [[UIImageView alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(22.5), ACTUAL_HEIGHT(465), ACTUAL_WIDTH(330), ACTUAL_HEIGHT(30))];
    //    _fengeimage.backgroundColor = [UIColor blueColor];
    [_fengeimage setImage:[UIImage imageNamed:@"fenge"]];
    
    [self.view addSubview:_fengeimage];
    
    
    
    
    _facebookButton = [[UIButton alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(22.5), ACTUAL_HEIGHT(500), ACTUAL_WIDTH(330), ACTUAL_HEIGHT(50))];
    //    _facebookButton.backgroundColor = [UIColor blueColor];
    [_facebookButton setImage:[UIImage imageNamed:@"face-book"] forState:UIControlStateNormal];
    [_facebookButton addTarget:self action:@selector(faceBookBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_facebookButton];
    
    //    [_facebookButton mas_makeConstraints:^(MASConstraintMaker *make) {
    ////        make.bottom.offset(-20);
    ////        make.right.offset(-20);
    //    }];
}
//UIButton *creatAccountButton=[[UIButton alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(25), ACTUAL_HEIGHT(197), ACTUAL_WIDTH(330), ACTUAL_HEIGHT(50))];
//creatAccountButton.backgroundColor=[UIColor blackColor];
//[creatAccountButton setTitle:@"CREATE ACCTROUNT" forState:0];
//creatAccountButton.titleLabel.font = FONT_SYSTEM_24;
//[creatAccountButton addTarget:self action:@selector(gotoCreatAccount) forControlEvents:UIControlEventTouchUpInside];
//[_BGView1 addSubview:creatAccountButton];
-(void)faceBookBtnClick
{
    //这个接口需要翻墙
    FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
    
    [login logOut];//这个一定要写，不然会出现换一个帐号就无法获取信息的错误
    
    [login
     
     logInWithReadPermissions: @[@"public_profile",@"email",@"user_about_me"]
     
     fromViewController:self
     
     handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
         
         if (error) {
             
             NSLog(@"Process error");
             
         } else if (result.isCancelled) {
             
             NSLog(@"Cancelled");
             
         } else {
             
             NSLog(@"succeed");
             
             FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
                                           
                                           initWithGraphPath:result.token.userID
                                           
                                           parameters:@{@"fields": @"id,name,email"}
                                           
                                           HTTPMethod:@"GET"];
             
             [request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result,NSError *error) {
                 
                 // Handle the result
                 
                 NSLog(@"%@,%@,%@",result[@"id"],result[@"name"],result[@"email"]);
                 
                 NSString * email;
                 if (result[@"email"]==nil) {
                     email = [NSString stringWithFormat:@"%@@163.com",result[@"id"]];
                 }else{
                     email = result[@"email"];
                 }
                 NSLog(@"email>>>>>%@",email);
                 NSString * password = @"gigds786752dkjiasr5da";
                 //                 facebook登录成功后向服务器发起注册
                 if (_isFaceRegister == NO) {
                     _isFaceRegister = YES;
                     NSString  * urlStr=[NSString stringWithFormat:@"%@main_page=create_account",HTTP_ADDRESS];
                     NSDictionary * params=@{
                                             @"email_address":email,
                                             @"telephone":@"**********",
                                             @"password":password,
                                             @"confirmation":password
                                             };
                     HttpManager*manager=[[HttpManager alloc]init];
                     [manager postDataFromNetworkWithUrl:urlStr parameters:params compliation:^(id data, NSError *error) {
                         //      注册完直接登录
                         [self facebookLoginForServerWithEmail:email password:password username:result[@"name"]];
                         NSString*number=[NSString stringWithFormat:@"%@",data[@"status"]];
                         
                         if ([number isEqualToString:@"1"]) {
                             NSDictionary *dict = @{@"email" : email,@"way":@"FB"};
                             [MobClick event:@"RegisterClick" attributes:dict];
                             
                         }
                         
                     
                         
                     }];
                 }
                 
                 
                 
                 return ;
                 
             }];
             
         }
     }];
    
    
}

-(void)facebookLoginForServerWithEmail:(NSString *)email  password:(NSString *)psw username:(NSString *)username
{
    NSString*urlStr=[NSString stringWithFormat:@"%@main_page=login",HTTP_ADDRESS];
    NSDictionary*params=@{@"email_address":email,
                          @"password":psw};
    HttpManager*manager=[[HttpManager alloc]init];
    [manager postDataFromNetworkWithUrl:urlStr parameters:params compliation:^(id data, NSError *error) {
        
        NSString*number=[NSString stringWithFormat:@"%@",data[@"status"]];
        
        if ([number isEqualToString:@"1"]) {
            NSDictionary *dict = @{@"email" : email,@"way":@"FB"};
            [MobClick event:@"LoginClick" attributes:dict];
            [MobClick profileSignInWithPUID:email provider:@"facebook"];
            [JRToast showWithText:@"Log in successfully！" duration:1];
            [self getCookie];
            [UserSession instance].isLogin=YES;
            [UserSession instance].email=username;
            
            if ([UserSession instance].isGotoPayment==NO) {
                
                [[SlideNavigationController sharedInstance] popToRootViewControllerAnimated:YES];
                
                [[SlideNavigationController sharedInstance] toggleRightMenu];
                [[SlideNavigationController sharedInstance].rightMenu viewWillAppear:YES];
                
                
            }else{
                ShoppingListViewController *vc=[[ShoppingListViewController alloc]init];
                vc.cartArray=self.shoppingCartArray;
                vc.allPrice=self.otherAllpriceStr;
                [[SlideNavigationController sharedInstance] switchToViewController:vc withCompletion:nil];
                
            }
            
        }else{
            [JRToast showWithText:data[@"status_message"] duration:2];
        }
        return ;
    }];
}


-(void)makeNaviButton{
    UIButton *titleButton=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, ACTUAL_WIDTH(250), ACTUAL_HEIGHT(30))];
    [titleButton setTitle:@"LOG IN/CREATE ACCOUNT" forState:0];
    titleButton.titleLabel.textColor = [UIColor blackColor];
    UIBarButtonItem *item= [[UIBarButtonItem alloc] initWithCustomView:titleButton];
    self.navigationItem.leftBarButtonItem=item;
    
    UIButton *forkButton=[[UIButton alloc] initWithFrame:CGRectMake(ACTUAL_WIDTH(320), 0, ACTUAL_WIDTH(30), ACTUAL_HEIGHT(30))];
    [forkButton setImage:[UIImage imageNamed:@"nav_close"] forState:0];
    [forkButton addTarget:self action:@selector(comeBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem*item1 = [[UIBarButtonItem alloc] initWithCustomView:forkButton];
    self.navigationItem.rightBarButtonItem=item1;
}

-(void)makeView{
    
    //register
    self.registerButton=[[UIButton alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(22.5), ACTUAL_HEIGHT(108), ACTUAL_WIDTH(165), ACTUAL_HEIGHT(50))];
    [_registerButton setTitle:@"REGISTER" forState:0];
    _registerButton.titleLabel.font = FONT_SYSTEM_28;
    [_registerButton setImage:[UIImage imageNamed:@"btn_register_n"] forState:UIControlStateSelected];
    [_registerButton setImage:[UIImage imageNamed:@"btn_register_s"] forState:0];
    [_registerButton addTarget:self action:@selector(openRegisterView) forControlEvents:UIControlEventTouchUpInside];
    if ([UserSession instance].isLogin==YES) {
        [JRToast showWithText:@"You have landed, don't need to register！"];
        _registerButton.userInteractionEnabled=NO;
    }else{
        _registerButton.userInteractionEnabled=YES;
    }
    [self.view addSubview:self.registerButton];
    
    
    //login
    self.loginButton=[[UIButton alloc]initWithFrame:CGRectMake(ACTUAL_WIDTH(187.5), ACTUAL_HEIGHT(108), ACTUAL_WIDTH(165), ACTUAL_HEIGHT(50))];
    [_loginButton setTitle:@"LOGIN" forState:0];
    _loginButton.titleLabel.font = FONT_SYSTEM_28;
    [_loginButton setImage:[UIImage imageNamed:@"btn_login_n"] forState:UIControlStateSelected];
    [_loginButton setImage:[UIImage imageNamed:@"btn_login_s"] forState:0];
    
    [_loginButton addTarget:self action:@selector(openLoginView) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.loginButton];
}

//2个Button的点击事件
-(void)openRegisterView{
    _registerButton.selected=YES;
    _loginButton.selected=NO;
    
    [self.view addSubview:self.BGView1];
    [_BGView2 removeFromSuperview];
    
    [self.view bringSubviewToFront:_facebookButton];
}

-(void)openLoginView{
    _registerButton.selected=NO;
    _loginButton.selected=YES;
    
    [self.view addSubview:self.BGView2];
    [_BGView1 removeFromSuperview];
    
    [self.view bringSubviewToFront:_facebookButton];
}

#pragma mark - 注册按钮事件
-(void)gotoCreatAccount{
    //注册接口
    //http://viprunningonline.com/api/index.php?  main_page=create_account&email_address=111@qq.com&password=111111&Confirmation=111111
    NSString  * urlStr=[NSString stringWithFormat:@"%@main_page=create_account",HTTP_ADDRESS];
    NSDictionary * params=@{
                            @"email_address":self.EmailTextField1.text,
                            @"telephone":@"**********",
                            @"password":self.passwordTextField1.text,
                            @"confirmation":self.verifyPasswordTF1.text
                            };
    HttpManager*manager=[[HttpManager alloc]init];
    [manager postDataFromNetworkWithUrl:urlStr parameters:params compliation:^(id data, NSError *error) {
        
        NSString*number=[NSString stringWithFormat:@"%@",data[@"status"]];
        
        if ([number isEqualToString:@"1"]) {
            NSDictionary *dict = @{@"email" : self.EmailTextField1.text,@"way":@"noFB"};
            [MobClick event:@"RegisterClick" attributes:dict];
            [JRToast showWithText:@"Registered successfully！" duration:2];
            [self nextRegister];
            
        }else{
            [JRToast showWithText:data[@"status_message"] duration:2];
        }
        
    }];
    
}

#pragma mark - 登陆按钮点击事件
-(void)gotoLogin{
    
    if (self.EmailTextField2.text.length==0||self.passwordTextField2.text.length==0) {
        [JRToast showWithText:@"Please complete the login information！"];
    }else{
        //http://viprunningonline.com/api/index.php?main_page=create_account&email_address=111111@qq.com&password=111111&Telephone=111111
        NSString*urlStr=[NSString stringWithFormat:@"%@main_page=login",HTTP_ADDRESS];
        NSDictionary*params=@{@"email_address":self.EmailTextField2.text,
                              @"password":self.passwordTextField2.text};
        HttpManager*manager=[[HttpManager alloc]init];
        [manager postDataFromNetworkWithUrl:urlStr parameters:params compliation:^(id data, NSError *error) {
            
            NSString*number=[NSString stringWithFormat:@"%@",data[@"status"]];
            
            if ([number isEqualToString:@"1"]) {
                NSDictionary *dict = @{@"email" : self.EmailTextField2.text,@"way":@"noFB"};
                [MobClick event:@"LoginClick" attributes:dict];
                [MobClick profileSignInWithPUID:self.EmailTextField2.text];
                [JRToast showWithText:@"Log in successfully！" duration:1];
                [self getCookie];
                [UserSession instance].isLogin=YES;
                [UserSession instance].email=self.EmailTextField2.text;
                
                if ([UserSession instance].isGotoPayment==NO) {
                    
                    [[SlideNavigationController sharedInstance] popToRootViewControllerAnimated:YES];
                    
                    [[SlideNavigationController sharedInstance] toggleRightMenu];
                    [[SlideNavigationController sharedInstance].rightMenu viewWillAppear:YES];
                    
                    
                }else{
                    ShoppingListViewController *vc=[[ShoppingListViewController alloc]init];
                    vc.cartArray=self.shoppingCartArray;
                    //                vc.allCountArray=self.countArray1;
                    vc.allPrice=self.otherAllpriceStr;
                    [[SlideNavigationController sharedInstance] switchToViewController:vc withCompletion:nil];
                    
                }
                
            }else{
                [JRToast showWithText:data[@"status_message"] duration:2];
            }
            
        }];
    }
}
//ncja83334lphctvlsdtvhb0dd4
#pragma mark 获取cookie值
-(void)getCookie{
    //http://viprunningonline.com/api/index.php?main_page=zenid
    NSString*urlStr=[NSString stringWithFormat:@"%@",HTTP_ADDRESS];
    NSDictionary*params=@{@"main_page":@"zenid"};
    HttpManager*manager=[[HttpManager alloc]init];
    
    [manager getDataFromNetworkWithUrl:urlStr parameters:params compliation:^(id data, NSError *error) {
        
        NSString*number=[NSString stringWithFormat:@"%@",data[@"status"]];
        
        if ([number isEqualToString:@"1"]) {
            [UserSession instance].cookie=data[@"data"][@"zenid"];
            NSLog(@"RegisterCookie>>>>>>>%@",[UserSession instance].cookie);
        }
    }];
    
}

-(void)comeBack
{
    if (self.isShopVCPush == YES) {
        ShoppingCarViewController * shopVC = [[ShoppingCarViewController alloc]init];
        [[SlideNavigationController sharedInstance]pushViewController:shopVC animated:NO];
    }else{
        [[SlideNavigationController sharedInstance] popViewControllerAnimated:YES];
    }
    
    
}


#pragma mark 键盘收回
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

#pragma mark 注册后自动登录
-(void)nextRegister{
    if(_EmailTextField2 || _passwordTextField2 ){
        self.EmailTextField2.text=self.EmailTextField1.text;
        self.passwordTextField2.text=self.passwordTextField1.text;
        [self gotoLogin];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
